package com.xzit.rental.service.impl;

import cn.hutool.core.util.StrUtil;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.xzit.rental.config.OSSConfig;
import com.xzit.rental.service.IOssService;
import com.xzit.rental.utils.FileUtils;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

@Service
public class OssServiceImpl implements IOssService {

    @Resource
    private OSSConfig ossConfig;

    @Override
    public String upload(MultipartFile file) {
        // 上传文件的原始名
        String originalFilename = file.getOriginalFilename();
        // 获取新的文件名
        String fileName = FileUtils.getFileName(originalFilename);

        OSS ossClint = new OSSClientBuilder().build(
                ossConfig.getEndpoint(),
                ossConfig.getAccessKeyId(),
                ossConfig.getAccessKeySecret()
        );
        try{
            // 完成上传处理
            ossClint.putObject(ossConfig.getBucketName(),fileName,file.getInputStream());
            return "https://" + ossConfig.getBucketName() + "." + ossConfig.getEndpoint() + "/" + fileName;
        }catch (Exception e){
            throw new RuntimeException("上传失败");
        }finally {
            if (ossClint != null) {
                ossClint.shutdown();
            }
        }
    }

    @Override
    public boolean delete(String url) {
        OSS ossClint = new OSSClientBuilder().build(
                ossConfig.getEndpoint(),
                ossConfig.getAccessKeyId(),
                ossConfig.getAccessKeySecret()
        );
        String host = "https://"+ossConfig.getBucketName()+"."+ossConfig.getEndpoint()+"/";
        String objectName = StrUtil.removePrefix(url,host);
        try {
            ossClint.deleteObject(ossConfig.getBucketName(),objectName);
            return true;
        }catch (Exception e){
            throw new RuntimeException("删除失败");
        }finally {
            if (ossClint != null) {
                ossClint.shutdown();
            }
        }
    }
}
